<template>
  <div class="chart-container">
    <h2>小麦品质表</h2>
    <div id="wheatQualityChart" class="chart"></div>
    
    <div class="chart-controls">
      <span>选择年份：</span>
      <el-radio-group v-model="selectedYear" @change="updateChart">
        <el-radio-button label="2022">2022</el-radio-button>
        <el-radio-button label="2023">2023</el-radio-button>
        <el-radio-button label="2024">2024</el-radio-button>
      </el-radio-group>
      
      <el-button type="primary" @click="showAllYears">显示所有年份对比</el-button>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { onMounted, onUnmounted, ref, computed, watch } from 'vue'

export default {
  name: 'WheatQualityChart',
  props: {
    year: {
      type: String,
      default: '2023'
    },
    region: {
      type: String,
      default: '全国'
    }
  },
  setup(props) {
    const selectedYear = ref(props.year)
    let chartInstance = null
    
    // 模拟小麦品质数据（三年）
    const baseWheatQualityData = {
      2022: {
        categories: ['蛋白质含量', '湿面筋含量', '沉降值', '吸水率', '稳定时间', '拉伸面积'],
        values: [14.2, 32.5, 45.8, 58.2, 8.5, 72.0]
      },
      2023: {
        categories: ['蛋白质含量', '湿面筋含量', '沉降值', '吸水率', '稳定时间', '拉伸面积'],
        values: [14.8, 33.2, 47.5, 59.0, 9.2, 75.5]
      },
      2024: {
        categories: ['蛋白质含量', '湿面筋含量', '沉降值', '吸水率', '稳定时间', '拉伸面积'],
        values: [15.1, 34.0, 48.2, 59.5, 9.8, 78.0]
      }
    }
    
    // 区域调整系数
    const regionAdjustment = {
      '全国': 1.0,
      '华北': 1.05,
      '华东': 0.98,
      '华南': 0.92,
      '西北': 1.10,
      '东北': 1.03,
      '西南': 0.96
    }
    
    // 计算最终显示的数据
    const wheatQualityData = computed(() => {
      const adjustedData = { ...baseWheatQualityData }
      const adjustmentFactor = regionAdjustment[props.region] || 1.0
      
      // 对每个年份的数据应用区域调整系数
      Object.keys(adjustedData).forEach(year => {
        adjustedData[year].values = adjustedData[year].values.map(value => {
          // 根据不同指标特点调整系数应用方式
          const index = adjustedData[year].values.indexOf(value)
          if ([0, 1, 2, 4, 5].includes(index)) { // 蛋白质、湿面筋、沉降值、稳定时间、拉伸面积
            return Number((value * adjustmentFactor).toFixed(1))
          } else { // 吸水率
            return Number((value * (2 - adjustmentFactor)).toFixed(1)) // 反向调整
          }
        })
      })
      
      return adjustedData
    })
    
    const colors = ['#145A32', '#3498DB', '#F39C12']
    
    const initChart = () => {
      const chartDom = document.getElementById('wheatQualityChart')
      chartInstance = echarts.init(chartDom)
      
      updateChart()
    }
    
    const updateChart = () => {
      if (!chartInstance) return
      
      const currentYear = selectedYear.value
      const option = {
        title: {
          text: `小麦品质雷达图 - ${currentYear}年 (${props.region})`,
          left: 'center',
          textStyle: {
            color: '#145A32',
            fontWeight: 'bold'
          }
        },
        tooltip: {},
        legend: {
          data: [`${currentYear}年 (${props.region})`],
          bottom: 0
        },
        radar: {
          indicator: wheatQualityData.value[currentYear].categories.map((category, index) => ({
            name: category,
            max: 100
          }))
        },
        series: [{
          name: '小麦品质',
          type: 'radar',
          data: [{
            value: wheatQualityData.value[currentYear].values,
            name: `${currentYear}年 (${props.region})`,
            areaStyle: {
              color: colors[0]
            },
            lineStyle: {
              width: 2,
              color: colors[0]
            },
            itemStyle: {
              color: colors[0]
            }
          }]
        }]
      }
      
      chartInstance.setOption(option, true)
    }
    
    const showAllYears = () => {
      if (!chartInstance) return
      
      const option = {
        title: {
          text: `小麦品质历年对比雷达图 (${props.region})`
        },
        legend: {
          data: ['2022年', '2023年', '2024年'].map(year => `${year} (${props.region})`)
        },
        radar: {
          indicator: wheatQualityData.value['2023'].categories.map((category, index) => ({
            name: category,
            max: 100
          }))
        },
        series: [{
          type: 'radar',
          data: [
            {
              value: wheatQualityData.value['2022'].values,
              name: `2022年 (${props.region})`,
              areaStyle: {
                color: colors[0]
              },
              lineStyle: {
                width: 2,
                color: colors[0]
              },
              itemStyle: {
                color: colors[0]
              }
            },
            {
              value: wheatQualityData.value['2023'].values,
              name: `2023年 (${props.region})`,
              areaStyle: {
                color: colors[1]
              },
              lineStyle: {
                width: 2,
                color: colors[1]
              },
              itemStyle: {
                color: colors[1]
              }
            },
            {
              value: wheatQualityData.value['2024'].values,
              name: `2024年 (${props.region})`,
              areaStyle: {
                color: colors[2]
              },
              lineStyle: {
                width: 2,
                color: colors[2]
              },
              itemStyle: {
                color: colors[2]
              }
            }
          ]
        }]
      }
      
      chartInstance.setOption(option, true)
    }
    
    const resizeChart = () => {
      if (chartInstance) {
        chartInstance.resize()
      }
    }
    
    // 监听props变化
    watch(() => [props.year, props.region], ([newYear, newRegion]) => {
      selectedYear.value = newYear
      updateChart()
    }, { immediate: false })
    
    onMounted(() => {
      initChart()
      window.addEventListener('resize', resizeChart)
    })
    
    onUnmounted(() => {
      window.removeEventListener('resize', resizeChart)
      if (chartInstance) {
        chartInstance.dispose()
      }
    })
    
    return {
      selectedYear,
      updateChart,
      showAllYears
    }
  }
}
</script>

<style scoped>
.chart-container {
  background: var(--color-card-bg);
  border-radius: 8px;
  padding: 20px;
  box-shadow: var(--color-shadow);
  margin-bottom: 30px;
}

.chart {
  width: 100%;
  height: 400px;
  margin-bottom: 20px;
}

.chart-controls {
  display: flex;
  gap: 20px;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
}

h2 {
  color: var(--color-primary);
  font-size: 1.8rem;
  margin-bottom: 15px;
  text-align: center;
}
</style>